//
//  Random.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/9/29.
//

import UIKit

public protocol Random {
    static func random() -> Self
}

extension Int: Random {
    
    public static func random() -> Int {
        return Int(arc4random())
    }
    
    public static func random(from: Int, to: Int) -> Int {
        return from + (Int(arc4random()) % (to - from))
    }
    
}

extension Character: Random {
    
    public static func random() -> Character {
        return Character(UnicodeScalar(Int.random(from: 65, to: 90))!)
    }
    
}

extension String: Random {
    
    public static func random() -> String {
        let randomLength = Int.random(from: 0, to: 40)
        let randomCharacters = tabulate(times: randomLength) { _ in
            Character.random()
        }
        return String(randomCharacters)
    }
    
    public static func random(_ randomLength: Int) -> String {
        let randomCharacters = tabulate(times: randomLength) { _ in
            Character.random()
        }
        return String(randomCharacters)
    }
    
    public static func tabulate<A>(times: Int, transform: (Int) -> A) -> [A] {
        return (0..<times).map(transform)
    }
    
}
